package logic

import (
	"context"
	"fmt"
	"math/rand"
	"teatch/model/cache"
	"teatch/model/mysql"
	"teatch/teacherrpc/internal/svc"
	"teatch/teacherrpc/teacherrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *teacherrpc.LoginRequest) (*teacherrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.Student
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)

	sends, _ := cache.Rdb.Get(l.ctx, "SendKey"+in.Account).Result()
	if sends != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	if user.ID == 0 {
		data := mysql.Student{
			Account:  in.Account,
			Password: in.Password,
			Image:    "http://t05ktvrux.hn-bkt.clouddn.com/3.png",
			Name:     fmt.Sprintf("游客_%d", rand.Intn(9999)),
		}
		mysql.DB.Create(&data)
		user = data
	} else {
		if in.Password != user.Password {
			return nil, fmt.Errorf("密码错误,请重新输入")
		}

	}

	return &teacherrpc.LoginResponse{
		StudentId: int64(user.ID),
	}, nil
}
